﻿using Common.XmlHandle;
using SFJDService;
using SFJDService.EventHandle;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Test
{
    class Program
    {
        static int port = 65401;
        static int maxThrad = 100;
        static int runningThreadCount = 0;
        static int scannedCount = 0;
        
        static void Main(string[] args)
        {
            //IPAddress iP = IPAddress.Parse("192.168.0.1");
            //Console.WriteLine(" " + iP.ToString());
            //byte[] hash = GetHash("asda");
            //System.Console.WriteLine(hash.Length);
            //byte[] hash2 = GetHash("asda465468as45d846asd465465sda465416s5ad165s1d8498sad48456s1ad65165as44");
            //Console.WriteLine(hash2.Length);
            //byte[] hash3 = GetHash("asda");
            //System.Console.WriteLine(hash3.Length);
            //Console.WriteLine(BitConverter.ToInt32(hash, 0) + "   " + BitConverter.ToInt32(hash2, 0) + "   " + BitConverter.ToInt32(hash3, 0));

            //Runtime.Initialize();
            //byte[] ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork")).GetAddressBytes();
            //string ip2 = BitConverter.ToString(ip, 0);
            //Console.WriteLine(new IPAddress(ip).ToString());
            //PacketWithProof pac = new PacketWithProof(Runtime.thisUser.UserGuid, Guid.Empty, ip, Guid.Empty, 1, 1,1, Encoding.UTF8.GetBytes("sdasddads"));
            //Console.WriteLine(Encoding.UTF8.GetString(pac.ToBytes()));
            //Console.WriteLine(Encoding.ASCII.GetString(pac.ToBytes()));


            //new Thread(() =>
            //{
            //    SFJDPopup.Program.Main(new string[] { "1", "0000000000" });
            //}).Start();

            //通知窗口();
            调试服务();
            //测试xml();
            //NetCom();
            //网络测试();

            //事件总线();

            //扫描端口();

            //System.Console.WriteLine("[" + DateTime.Now.ToString("MMdd HH:mm:ss") + "]");
            Console.ReadLine();
        }

        static void 网络测试()
        {
            Console.Out.WriteLine(Dns.GetHostName());
            IPHostEntry entry = Dns.GetHostEntry(Dns.GetHostName());
            Console.Out.WriteLine(entry.AddressList.ToArray().ToString());
            entry.AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString();
            Console.Out.WriteLine(entry.AddressList.FirstOrDefault(a => a.ToString().StartsWith("192")).ToString());
        }

        static void NetCom()
        {
            //Console.Out.WriteLine(NetworkCommsDotNet.Tools.ShortGuid.NewGuid());
        }

        static void Reflect()
        {

        }

        static void 事件总线()
        {
            var eventData = new SCPopupData() { Message = "TESTESTESTEST" };
            EventBus.instance.Trigger<SCPopupData>(eventData);
        }

        static void 通知窗口()
        {
            //SFJDPopup.Program.Main(new string[] { "1", "0000000000" });
            Thread thread = new Thread(new ThreadStart(ThreadStartPopup));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        static void ThreadStartPopup()
        {
            //SFJDPopup.Program.Main(new string[] { "1", "0000000000" });

            SFJDPopup.MainWindow window = new SFJDPopup.MainWindow("发送到 " + "0000" + " 的文件已完成。");
            
            window.Show();
            window.Closed += (s, e) => window.Dispatcher.BeginInvokeShutdown(System.Windows.Threading.DispatcherPriority.Background);
            window.Topmost = true;
            System.Windows.Threading.Dispatcher.Run();
        }

        static void 测试xml()
        {
            XmlContact xml = new XmlContact(@"C:\Program Files\SFJDManagement\XmlContact.xml");
            List<string> aa = xml.Coding2SocketString();
        }

        static void 扫描端口()
        {
            //new SFJDService.SFJDService().Debug();
            Runtime.Initialize();
            //new LanScanning(65401).ScanningAllHosts();
            //ScanningAllHosts();
        }

        static void 调试服务()
        {
            Console.Title = "Debug";

            new SFJDService.SFJDService().Debug();
        }

        static void 调试文件传送()
        {
            FileInfo fileInfo = null;
            try
            {
                fileInfo = new FileInfo("E:\\收到的文件\\" + "Update\\SFJDService.exe");
            }
            catch { }
            Version fileVersion = null;
            if (fileInfo != null && fileInfo.Exists)//如果接收文件夹存在升级文件
            {
                System.Diagnostics.FileVersionInfo versionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo("E:\\收到的文件\\" + "Update\\SFJDService.exe");

                fileVersion = new Version(versionInfo.FileVersion.ToString());
                System.Console.WriteLine(fileVersion.ToString());
            }
        }

        static void ScanningAllHosts()
        {
            string m_Ip = Runtime.myIP;
            string ip_Segment = m_Ip.Remove(m_Ip.LastIndexOf('.'));
            for (int i = 1; i < 255; i++)
            {
                new Thread(() =>
                {
                    string ip = ip_Segment + '.' + i.ToString();
                    Console.WriteLine("                   扫描" + ip + "   " + i);
                    ScanningOneHost(ip);
                }).Start();
                runningThreadCount++;
                Thread.Sleep(10);
                //循环，直到某个线程工作完毕才启动另一新线程，也可以叫做推拉窗技术
                while (runningThreadCount >= maxThrad) ;
            }
            while (scannedCount + 1 < 254) ;
        }

        static void ScanningOneHost(string ip)
        {
            TcpClient tcp = new TcpClient();
            tcp.SendTimeout = tcp.ReceiveTimeout = 30000;
            try
            {
                tcp.Connect(ip, port);
                if (tcp.Connected)
                {
                    Console.WriteLine(ip.ToString());
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                tcp.Close();
                runningThreadCount--;
                scannedCount++;
            }
        }


        /// <summary>
        /// DateTime转换为Long型
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        static long ConvertDataTime2Long(DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan toNow = dt.Subtract(dtStart);
            long timeStamp = toNow.Ticks;
            timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
            return timeStamp;
        }

        /// <summary>
        /// Long型转换为DateTime
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        static DateTime ConvertLong2DateTime(string d)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(d + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

        static byte[] GetHash(string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(Encoding.ASCII.GetBytes(str));
            return retVal;
        }
    }
}
